package com.imooc.authorization.controller;

import com.imooc.authorization.common.BaseEntiry;
import com.imooc.authorization.dto.Authorize;
import com.imooc.authorization.entity.Role;
import com.imooc.authorization.entity.User;
import com.imooc.authorization.entity.UserRole;
import com.imooc.authorization.service.RoleService;
import com.imooc.authorization.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.*;

/**
 * Created by Administrator on 2016/8/28.
 */
@RequestMapping("authorize")
@Controller
public class UserAuthorizeContoller {

    @Autowired private UserService userService;
    @Autowired private RoleService roleService;

    /**
     * 授权首页
     * @return
     */
    @RequestMapping("/index")
    public String index(){

        return "security/authorize/authorize_list";
    }

    @RequestMapping("/userRole")
    public String authorizeIndex(){

        return "security/authorize/user_role_list";
    }

    public List<Authorize> getAuthorizes(Integer page,Integer rows){
        List<UserRole> userRoles=userService.getUserRoles(page,rows);
        Collection<Long> userIds = new HashSet<>();
        Collection<Long> roleIds = new HashSet<>();

        userRoles.forEach((ur) ->{

            userIds.add(ur.getUserId());
            roleIds.add(ur.getRoleId());
        });
        Collection<User> users=userService.getUsers(userIds);
        List<Role> roles=roleService.getRoles(roleIds);

        Map<Long,User> userMap= BaseEntiry.idEtityMap(users);
        Map<Long,Role> roleMap=BaseEntiry.idEtityMap(roles);

        List<Authorize> authorizes=new LinkedList<>();
        userRoles.forEach((ur)->{

            Authorize authorize=new Authorize();
            authorize.setRoleId(ur.getId());
            authorize.setUserId(ur.getUserId());
            authorize.setUserName(userMap.get(ur.getUserId()).getName());
            authorize.setRoleId(ur.getRoleId());
            authorize.setRoleName(roleMap.get(ur.getRoleId()).getName());

            authorizes.add(authorize);
        });
        return authorizes;
    }

}
